import Router from '@koa/router';
import fs from 'fs';
import path from 'path';
import { BeError, BeSuccess } from '../utils/response';
import { calc } from '../helper/hllHelper';
import { md5 } from '../utils';

// import { getUserInfo, getUsereExtInfo } from '../thirdServices/api';

const router = new Router();

// 计算
router.get('/calcPrice', async function (ctx) {
  if (!global.userToken) {
    ctx.body = BeError('请先设置用户！');
    return;
  }
  const { routeId, cityName, district, vehicleName, start, end, orderTime, fromLon, fromLat, toLon, toLat } = ctx.query;
  try {
    const data = await calc(cityName, district, vehicleName, start, end, orderTime, fromLon, fromLat, toLon, toLat);
    ctx.body = BeSuccess({ ...data, routeId, cityName, district, start, end });
  } catch (error) {
    console.log(error);
    ctx.body = BeError(error.message);
  }
});

// 添加token
router.post('/addToken', async function (ctx) {
  const { token, openId } = ctx.request.body;
  try {
    const url = path.resolve('./', 'assets');
    if (!fs.existsSync(url)) {
      fs.mkdirSync(url);
    }
    
    const openIdmd5 = md5(openId);
    global.userToken = token;
    global.userOpenId = openIdmd5;
    fs.writeFileSync(url + '/token.json', JSON.stringify({ token, openId: openIdmd5 }));
    ctx.body = BeSuccess('成功');
  } catch (error) {
    ctx.body = BeError(error.message);
  }
});

export default router.routes();
